<template>

	<uni-load-more :status="isLoadingStatus" v-if="isLoading" />

	<view v-else class="book-page">
		<!-- 顶部操作栏弹窗 -->
		<view class="book-action-bar" :style="{ 'marginTop': uni.getWindowInfo().safeAreaInsets.bottom + 'px' }">
			<view class="action-bar-button" @click="handleNavigateBack">返回上一页</view>
			<view class="action-bar-button" @click="!isInBookShelfFlag ? handleAddBookShelf() : null">
				{{ isInBookShelfFlag ? '已加入书架' : '加入书架' }}
			</view>
			<view class="action-bar-button" @click="!isCommentFlag ? handleOpenInputDialog() : null">
				{{ isCommentFlag ? '已评分' : '评分' }}
			</view>
		</view>

		<!-- 1.书籍图片和作者信息区域 -->
		<view class="book-header" :style="{ 'marginTop': uni.getWindowInfo().safeAreaInsets.bottom + 50 + 'px' }">
			<image class="book-cover" :src="`${baseURL}${bookInfo?.image}`" mode="widthFix"></image>
			<view class="book-title">{{ bookInfo?.name }}</view>
			<view class="author-info">
				<image class="author-avatar" :src="`${baseURL}${authorInfo?.avatar}`" mode="aspectFill"></image>
				<view class="author-name" @click="handleNavigateToAuthor(authorInfo?.name || '')">{{ authorInfo?.name }}
				</view>
				<button class="follow-button"
					@click="isFan ? handleCancelFanAuthor() : handleAddFanAuthor()">{{ isFan ? '取消关注' : '关注' }}</button>
			</view>
		</view>

		<!-- 2.书籍统计信息区域 -->
		<view class="book-stats">
			<view class="stats-container">
				<view class="stat-item">
					<text class="stat-value">{{ bookInfo?.score }}分</text>
					<text class="stat-label">{{ bookInfo?.scoreNum }}人点评</text>
				</view>
				<view class="stat-item">
					<text class="stat-value">{{ (bookInfo?.hot || 0) / 10000 }}万人</text>
					<text class="stat-label">正在阅读</text>
				</view>
				<view class="stat-item">
					<text class="stat-value">{{ (bookInfo?.wordCount || 0) / 10000 }}万字</text>
					<text class="stat-label">连续更新61天</text>
				</view>
			</view>
		</view>

		<!-- 3.书籍简介区域 -->
		<view class="book-description">
			<view class="description-header">
				<text>简介</text>
				<text v-for="tag in 3" :key="tag" class="description-tag">东方玄幻</text>
			</view>
			<!-- 简介内容容器 -->
			<view class="description-content">{{ bookInfo?.description?.slice(0, 40) }}</view>
			<view class="description-toggle" @click.stop="handleShowDescriptionPopup">查看详情</view>
		</view>

		<!-- 4.热门书评区域 -->
		<view class="book-reviews">
			<view class="reviews-header">
				<text>热门书评</text>
				<text class="reviews-more" @click.stop="handleGoToReview">更多书评</text>
			</view>
			<view class="reviews-content">
				<!-- 循环渲染3条书评 -->
				<view v-for="item in reviewData" :key="item.id" class="review-item">
					<!-- 左侧用户头像 -->
					<image class="review-avatar" :src="`${baseURL}${item?.userAvatar}`" mode="aspectFill"></image>
					<!-- 右侧书评内容 -->
					<view class="review-details">
						<!-- 用户名和书评时间 -->
						<view class="review-user-info">
							<text class="review-username">{{ item?.userName }}</text>
							<text class="review-time">{{ item?.createTime }}</text>
						</view>
						<!-- 评分星星 -->
						<view class="review-stars">
							<uni-icons v-for="star in item?.score / 2" :key="star" type="star-filled" size="16"
								color="#FFD700"></uni-icons>
							<uni-icons v-for="star in 5 - item?.score / 2" :key="star" type="star-filled" size="16"
								color="#e1e1e1"></uni-icons>
						</view>
						<!-- 书评内容 -->
						<view class="review-content">{{ item?.commentContent }}</view>
					</view>
				</view>
			</view>
		</view>

		<!-- 5.阅读操作按钮 -->
		<view class="read-action">
			<view class="action-button" @click.stop="handleGoChapter">←左滑开始阅读</view>
		</view>
	</view>

	<!-- 评论输入弹窗 -->
	<uni-popup ref="inputDialogRef" type="dialog">
		<uni-popup-dialog ref="ratingDialogRef" mode="input" title="评分与评论" value="" placeholder="请输入评论内容"
			@confirm="handleDialogInputConfirm">
			<view class="comment-popup">
				<view class="star-rating">
					<view class="star-icon" v-for="(star, index) in 5" :key="index" @click="handleSetScore(index + 1)"
						:class="{ 'active': score > index }">{{ score > index ? '★' : '☆' }}</view>
				</view>
				<view class="comment-description">
					<uni-easyinput prefixIcon="chatboxes" placeholder="请输入评论" v-model="searchKeyword" class="w-full"
						maxlength="-1" type="textarea" @clear="handleClear"></uni-easyinput>
				</view>
			</view>
		</uni-popup-dialog>
	</uni-popup>

	<!-- 简介详情弹窗 -->
	<uni-popup ref="descriptionPopup" type="bottom" :maskClick="true" :isMask="true" maskBackgroundColor="transparent"
		backgroundColor="#fff" borderRadius="10px 0px">
		<scroll-view class="description-popup-content" scroll-y>{{ bookInfo?.description }}</scroll-view>
	</uni-popup>
</template>

<script lang="ts" setup>
	import { getBookInfoByIdAPI } from '@/services/book';
	import { BookItem } from '../../types/book';
	import { addAuthorFanAPI, cancelAuthorFanAPI, checkAuthorFanAPI, queryAuthorInfoByBookIdAPI } from '@/services/author';
	import { ref } from 'vue';
	import { baseURL } from '@/utils/config';
	import { addBookShelfAPI, getBookShelfByIdAPI } from '@/services/bookshelf';
	import { addCommentAPI, checkCommentedAPI, pageReviewsAPI } from '@/services/review';
	import { commonPageQueryData } from '@/services/global';
	import { ReviewItem } from '../../types/review';
	import { PageParams } from '../../types/global';
	import { AuthorItem } from '../../types/author';
	import { onLoad } from '@dcloudio/uni-app';

	// ===================== 响应式变量定义 =====================
	/** 是否展开详情 */
	const isExpanded = ref(true);
	/** 评论输入弹窗引用 */
	const inputDialogRef = ref();
	/** 评分弹窗引用 */
	const ratingDialogRef = ref();
	/** 搜索关键词 */
	const searchKeyword = ref("");
	/** 是否已评论标记 */
	const isCommentFlag = ref(false);
	/** 评分值 */
	const score = ref<number>(0);
	/** 书籍信息 */
	const bookInfo = ref<BookItem>();
	/** 作者信息 */
	const authorInfo = ref<AuthorItem>({
		id: 0,
		name: '',
		avatar: '',
		bookCount: 0,
		fansCount: 0,
		likeCount: 0,
	});
	/** 父组件传入的书籍ID */
	const props = defineProps<{
		bookId : number;
	}>();
	/** 页面加载状态 */
	const isLoading = ref(false);
	/** 加载状态文本 */
	const isLoadingStatus = ref('more');
	/** 当前书籍ID */
	const currentBookId = ref(0);
	/** 是否在书架标记 */
	const isInBookShelfFlag = ref(false);
	/** 简介弹窗引用 */
	const descriptionPopup = ref<any>();
	/** 简介弹窗显示标记 */
	const descriptionPopupFlag = ref(false);
	/** 是否关注作者 */
	const isFan = ref(false);
	/** 书评数据是否加载完成 */
	const finish = ref(false);
	/** 书评数据列表 */
	const reviewData = ref<ReviewItem[]>([]);
	/** 分页参数 */
	const pageParams : Required<PageParams> = {
		current: 1,
		size: 3,
	};

	// ===================== 工具方法 =====================
	/**
	 * 清空搜索框内容
	 */
	const handleClear = () => {
		searchKeyword.value = '';
	};



	/**
	 * 打开评论输入框
	 */
	const handleOpenInputDialog = () => {
		inputDialogRef.value?.open();
	};

	/**
	 * 设置评分
	 * @param value 评分值(1-5)
	 */
	const handleSetScore = (value : number) => {
		score.value = value;
	};

	/**
	 * 展示/隐藏简介详情弹窗
	 */
	const handleShowDescriptionPopup = () => {
		isExpanded.value = !isExpanded.value;
		if (descriptionPopupFlag.value) {
			descriptionPopup.value.close();
			descriptionPopupFlag.value = false;
		} else {
			descriptionPopup.value.open();
			descriptionPopupFlag.value = true;
		}
	};

	/**
	 * 跳转书评页面
	 */
	const handleGoToReview = () => {
		uni.navigateTo({
			url: '/pages/review/index?bookId=' + props.bookId,
		});
	};

	/**
	 * 跳转到阅读界面
	 */
	const handleGoChapter = () => {
		uni.navigateTo({
			url: `/pages/book/chapter?bookId=${bookInfo.value?.id}`,
		});
	};

	/**
	 * 返回上一页
	 */
	const handleNavigateBack = () => {
		uni.navigateBack({
			delta: 1,
		});
	};

	// ===================== API 调用方法 =====================
	/**
	 * 提交评论
	 * @param value 评论内容
	 */
	const handleDialogInputConfirm = async (value : string) => {
		await addCommentAPI({
			bookId: currentBookId.value,
			commentContent: searchKeyword.value,
			score: score.value * 2,
		}).then((res) => {
			uni.showToast({
				title: '评论成功',
				icon: 'success',
			});
			score.value = 0;
			searchKeyword.value = '';
			// 刷新数据
			checkCommented();
		});
	};

	/**
	 * 校验是否已经评论过
	 */
	const checkCommented = async () => {
		await checkCommentedAPI({
			bookId: currentBookId.value,
		}).then((res) => {
			if (res.data) {
				isCommentFlag.value = true;
			}
		});
	};

	/**
	 * 查看当前书籍是否在书架上
	 * @param bookId 书籍ID
	 */
	const queryBookShelfByBookIdData = async (bookId : number) => {
		getBookShelfByIdAPI(bookId).then((res) => {
			if (res.data) {
				isInBookShelfFlag.value = true;
			}
		});
	};

	/**
	 * 根据书籍id查询书本信息
	 * @param bookId 书籍ID
	 */
	const queryBookInfoByBookIdData = async (bookId : number) => {
		getBookInfoByIdAPI(bookId).then((res) => {
			bookInfo.value = res.data;
		});
	};

	/**
	 * 根据书籍id查询作者信息
	 * @param bookId 书籍ID
	 */
	const queryAuthorInfoByBookIdData = async (bookId : number) => {
		await queryAuthorInfoByBookIdAPI(bookId).then((res) => {
			authorInfo.value = res.data;
		});
	};

	/**
	 * 加入书架
	 */
	const handleAddBookShelf = async () => {
		await addBookShelfAPI(currentBookId.value).then((res) => {
			uni.showToast({
				title: '加入书架成功',
				icon: 'success',
			});
		});
		await queryBookShelfByBookIdData(currentBookId.value);
	};

	/**
	 * 获取书评列表
	 */
	const pageGetReviewListData = async () => {
		const queryParams = ref({
			bookId: props.bookId,
		});
		await commonPageQueryData(
			pageReviewsAPI,
			reviewData,
			finish,
			isLoading,
			pageParams,
			queryParams
		);
	};

	/**
	 * 关注作者
	 */
	const handleAddFanAuthor = async () => {
		if (authorInfo.value != null) {
			await addAuthorFanAPI(authorInfo.value.name).then((res) => {
				uni.showToast({
					title: '关注成功',
					icon: 'success',
				});
			});
			await checkAuthorFanData();
		}
	};

	/**
	 * 取消关注作者
	 */
	const handleCancelFanAuthor = async () => {
		uni.showModal({
			title: '提示',
			content: '确定取消关注吗？',
			success: async (res) => {
				if (res.confirm) {
					await cancelAuthorFanAPI(authorInfo.value.name).then((res) => {
						uni.showToast({
							title: '取消关注成功',
							icon: 'success',
						});
					});
					await checkAuthorFanData();
				}
			},
		});
	};

	/**
	 * 检查是否关注作者
	 */
	const checkAuthorFanData = async () => {
		if (authorInfo.value?.name) {
			checkAuthorFanAPI(authorInfo.value.name).then((res) => {
				isFan.value = res.data as unknown as boolean;
			});
		}
	};

	/**
	 * 跳转作者页面
	 * @param authorName 作者名称
	 */
	const handleNavigateToAuthor = (authorName : string) => {
		uni.navigateTo({
			url: '/pages/author/index?authorName=' + authorName,
		});
	};

	// ===================== 生命周期钩子 =====================
	/**
	 * 页面加载时触发
	 */
	onLoad(async () => {
		isLoading.value = true;
		isLoadingStatus.value = 'loading';
		currentBookId.value = props.bookId;

		// 查询书本简介信息
		await queryBookInfoByBookIdData(currentBookId.value);

		// 查询作者信息
		await queryAuthorInfoByBookIdData(currentBookId.value);

		// 查看当前书籍是否在书架上
		await queryBookShelfByBookIdData(currentBookId.value);

		// 校验是否评分
		await checkCommented();

		// 查询书评
		await pageGetReviewListData();

		// 检查作者是否关注
		await checkAuthorFanData();

		// 置空标题
		uni.setNavigationBarTitle({
			title: '',
		});

		// 延迟加载
		setTimeout(() => {
			isLoading.value = false;
			isLoadingStatus.value = 'more';
		}, 100);
	});
</script>

<style lang="scss">
	.book-page {
		height: 100vh;
		background-color: #e5e5e5;
		overflow-y: hidden;

		// 1.书籍图片和作者栏
		.book-header {
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			margin: 0.5rem;

			.book-cover {
				width: 120px;
				height: 180px;
				border-radius: 0.5rem;
				margin-right: 0.75rem;
			}

			.book-title {
				color: #000;
				font-size: 1.5rem;
				font-weight: bold;
				margin-top: 0.5rem;
			}

			.author-info {
				display: flex;
				flex-direction: row;
				align-items: center;
				justify-content: center;

				.author-avatar {
					width: 2.5rem;
					height: 2.5rem;
					border-radius: 50%;
				}

				.author-name {
					color: #000;
					margin: 0.5rem 1rem;
				}

				.follow-button {
					font-size: 0.875rem;
					color: #171102;
					border-radius: 0.5rem;
					padding: 0.25rem 0.5rem;
					background-color: #d7d4d4;
				}
			}
		}

		// 2.书籍统计信息
		.book-stats {
			display: flex;
			flex-direction: column;
			align-items: flex-start;
			justify-content: center;
			margin: 0.625rem;

			.stats-container {
				display: flex;
				flex-direction: row;
				justify-content: space-between;
				align-items: center;
				width: 100%;

				.stat-item {
					display: flex;
					flex-direction: column;

					.stat-value {
						font-size: 1.125rem;
						color: #000;
					}

					.stat-label {
						font-size: 0.875rem;
						color: #94a3b8;
					}
				}
			}
		}

		// 3.简介区域
		.book-description {
			margin-top: 1.25rem;
			display: flex;
			flex-direction: column;
			margin: 0.5rem;

			.description-header {
				font-size: 1.125rem;
				color: #000;

				.description-tag {
					padding: 0.25rem 0.5rem;
					margin-right: 0.5rem;
					font-size: 0.75rem;
					background-color: #d1d5db;
					border-radius: 0.5rem;
					color: #94a3b8;
				}
			}

			.description-content {
				overflow: hidden;
				font-size: 0.875rem;
				color: #94a3b8;
			}

			.description-toggle {
				margin-top: 0.5rem;
				font-size: 0.875rem;
				color: #3b82f6;
			}
		}

		// 4.热门书评
		.book-reviews {
			margin-top: 1.25rem;
			display: flex;
			flex-direction: column;
			margin: 0.5rem;

			.reviews-header {
				font-size: 1.125rem;
				color: #000;
				display: flex;
				justify-content: space-between;

				.reviews-more {
					margin-left: 0.5rem;
					font-size: 0.875rem;
					color: #3b82f6;
				}
			}

			.reviews-content {
				margin-top: 0.625rem;
				display: flex;
				flex-direction: column;
				margin-bottom: 3.75rem;

				.review-item {
					display: flex;
					flex-direction: row;
					margin-bottom: 0.625rem;

					.review-avatar {
						width: 3rem;
						height: 3rem;
						border-radius: 50%;
					}

					.review-details {
						display: flex;
						flex-direction: column;
						margin-left: 0.75rem;
						flex: 1;

						.review-user-info {
							display: flex;
							flex-direction: row;
							justify-content: space-between;

							.review-username {
								font-size: 0.875rem;
								color: #000;
							}

							.review-time {
								font-size: 0.75rem;
								color: #94a3b8;
							}
						}

						.review-stars {
							display: flex;
							flex-direction: row;
							margin-top: 0.25rem;
						}

						.review-content {
							font-size: 0.875rem;
							color: #475569;
							margin-top: 0.25rem;
						}
					}
				}
			}
		}

		// 5.阅读操作按钮
		.read-action {
			display: flex;
			flex-direction: row;
			justify-content: center;
			align-items: center;

			.action-button {
				display: flex;
				flex-direction: column;
				justify-content: center;
				align-items: center;
				padding: 10px;
				color: black;
			}
		}

		// 顶部操作栏
		.book-action-bar {
			display: flex;
			flex-direction: row;
			justify-content: space-around;
			align-items: center;
			padding-right: 10px;
			color: black;

			.action-bar-button {
				display: flex;
				flex-direction: column;
				justify-content: center;
				align-items: center;
				padding: 10px;
				color: black;
			}
		}
	}

	// 评分星星样式
	.star-rating {
		display: flex;
		align-items: center;
		flex-direction: row;
		margin-bottom: 15px;
		justify-content: space-around;

		.star-icon {
			color: #d7d4d4;
			font-size: 1.2rem;
			margin-right: 10px;

			&.active {
				color: #FFD700;
			}
		}
	}

	// 简介弹窗内容样式
	.description-popup-content {
		padding: 4px 16px;
		// background-color: #e5e5e5;
		height: 60vh;
		// border-top: 1px solid black;
		font-size: 0.875rem;
		color: #475569;
		margin-top: 0.25rem;
	}

	.comment-popup {
		display: flex;
		flex-direction: column;
		width: 100%;
		height: 300px;
	}

	.comment-description {
		width: 100%;
		height: 250px;
	}
</style>